<template>
  <el-dialog v-model="model" @close="closedDialog">
    <el-form
      ref="taskAttachmentFormRef"
      :model="form"
      label-width="100px"
      :rules="rules"
    >
      <el-row>
        <el-col :span="24" v-if="!update">
          <el-form-item :label="$t('taskAttachment.file')" prop="url">
            <jmash-upload-file
              style="width: 100%"
              ref="uploadRef"
              accept="pptx,xlsx,docx,txt,png,jpg,pdf,zip,tar.gz,"
              :limit="1"
              :on-success="handleSuccess"
              v-model:file-list="fileList"
            >
              <el-button type="primary">上传文件</el-button>
            </jmash-upload-file>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('taskAttachment.name')" prop="name">
            <el-input
              v-model="form.name"
              :placeholder="$t('taskAttachment.name')"
              maxlength="60"
              show-word-limit
              style="width: 430px"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="!update">
          <el-form-item :label="$t('taskAttachment.type')" prop="type">
            <el-input
              v-model="form.type"
              :placeholder="$t('taskAttachment.type')"
              maxlength="60"
              show-word-limit
              style="width: 430px"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            :label="$t('taskAttachment.description')"
            prop="description"
          >
            <el-input
              v-model="form.description"
              :placeholder="$t('taskAttachment.description')"
              maxlength="1000"
              show-word-limit
              style="width: 430px"
              :rows="3"
              type="textarea"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closedDialog">{{ $t("common.cancel") }}</el-button>
        <el-button type="primary" @click="submitForm">
          {{ $t("common.confirm") }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, type PropType } from "vue";
import {
  type FormInstance,
  type FormRules,
  ElMessage,
  type UploadFile,
  type UploadFiles,
  type UploadProps,
  type UploadRawFile,
} from "element-plus";

import { useI18n } from "vue-i18n";
const { t } = useI18n();

import type {
  TaskAttachmentModel,
  TaskAttachmentFromReq,
  TaskAttachmentCreateReq,
  TaskAttachmentUpdateReq,
} from "@/api/flow/attachment/types";
import { taskAttachmentApi } from "@/api/flow/attachment/index";

const taskAttachmentFormRef = ref<FormInstance>();

let form: TaskAttachmentFromReq = reactive<TaskAttachmentFromReq>({
  requestId: Math.random() * 10 + "",
  updateMask: "name,description",
});

const rules = reactive<FormRules<TaskAttachmentFromReq>>({
  name: [
    {
      required: true,
      message: t("taskAttachment.name"),
      trigger: "change",
    },
  ],
  description: [
    {
      required: true,
      message: t("taskAttachment.description"),
      trigger: "change",
    },
  ],
  type: [
    {
      required: true,
      message: t("taskAttachment.type"),
      trigger: "change",
    },
  ],
  url: [
    {
      required: true,
      message: t("taskAttachment.file"),
      trigger: "change",
    },
  ],
});

const model = defineModel<boolean>();

const props = defineProps({
  entity: {
    type: Object as PropType<TaskAttachmentModel>,
    default: () => {},
  },
});

form.taskId = props.entity.taskId;
const keys = Object.keys(props.entity);
const update = ref(keys.length > 1);

if (update.value) {
  form.attachmentId = props.entity.id;
  form.name = props.entity.name;
  form.description = props.entity.description;
  form.type = props.entity.type;
}

//文件上传
const uploadRef = ref(null);
const fileList = ref([] as any[]);

const handleSuccess: UploadProps["onSuccess"] = (
  response: any,
  uploadFile: UploadFile,
  uploadFiles: UploadFiles,
) => {
  form.name = uploadFile.name;
  form.url = response.fileSrc;
  form.type = response.fileType;
};

const emits = defineEmits(["refresh"]);
// 提交表单校验
const submitForm = async () => {
  await taskAttachmentFormRef.value?.validate((valid) => {
    if (valid) {
      if (update.value) {
        taskAttachmentApi
          .update(form as TaskAttachmentUpdateReq)
          .then((response) => {
            if (response.status === 200) {
              ElMessage({
                message: t("common.submitSuccess"),
                type: "success",
              });
              if (model.value) {
                model.value = false;
              }
              emits("refresh", response.status === 200);
            }
          });
      } else {
        taskAttachmentApi
          .create(form as TaskAttachmentCreateReq)
          .then((response) => {
            if (response.status === 200) {
              ElMessage({
                message: t("common.submitSuccess"),
                type: "success",
              });
              if (model.value) {
                model.value = false;
              }
              emits("refresh", response.status === 200);
            }
          });
      }
    }
  });
};

// 关闭弹框
function closedDialog() {
  if (model.value) {
    model.value = false;
  }
}
</script>
<style scoped lang="scss">
.position-center {
  position: absolute;
  right: 0;
  top: 30%;
  transform: translate(0, -30%);
}

.plus-position {
  position: absolute;
  right: 0;
  top: 0;
  margin-top: 8px;
}
</style>
